/*
---------------------------------------------------------------------------------------------
All rights reserved for IGLOBALIST LLC - iglobalistCMS
User can't redistribute it without IGLOBALIST written permission.
---------------------------------------------------------------------------------------------
Version number 1:
---------------------------------------------------------------------------------------------
Modification number 1:
Modification by developer:
Modification date:
Modification reason:
---------------------------------------------------------------------------------------------
*/
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Collections.Generic;
using System.IO;

namespace IGlobalist.Cms.Common
{
    /// <summary>
    /// Using file securityPolicy.config to permission user on page
    /// 
    /// </summary>
    public class SecurityManager
    {
        private static string settingFilePath = "SecurityPolicy.config";
        private static XmlDocument xdoc;
        private static IDictionary<string, string> mapTable = new Dictionary<string, string>();
        static SecurityManager()
        {
            settingFilePath = Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath,settingFilePath);
        }

        public static bool IsHasPermission()
        {
            loadConfig();
            string currentPage = HttpContext.Current.Request.FilePath;
            string fileName = System.IO.Path.GetFileName(currentPage).ToLower();
            
            if (!mapTable.ContainsKey(fileName))//not in security map file -> pass
                return true;
            string[] roles = mapTable[fileName].Split(',');
            for (int i = 0; i < roles.Length; i++)
            {
                IGlobalist.Cms.Model.BuiltinRole role=(IGlobalist.Cms.Model.BuiltinRole) Enum.Parse(typeof(IGlobalist.Cms.Model.BuiltinRole),roles[i]);
                if (IGlobalistMembership.IsInRole(role)){
                    return true;
                };
                
            }

            //return HttpContext.Current.User.Identity.IsAuthenticated;

            return false;
        }
        private static void CacheRemoveCallback(string key, object obj, System.Web.Caching.CacheItemRemovedReason reason)
        {
            xdoc = null;
            loadConfig();
        }
        private static void loadConfig()
        {
            if (xdoc != null) return;
            xdoc = new XmlDocument();    
            lock (xdoc)
            {
                xdoc.Load(settingFilePath);
                populateConfig();
                try
                {
                    HttpContext.Current.Cache.Add("SecurityPolicy.config", xdoc, new System.Web.Caching.CacheDependency(settingFilePath), DateTime.Now.AddYears(1), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.High, new System.Web.Caching.CacheItemRemovedCallback(CacheRemoveCallback)); 
                }
                catch (Exception e)
                {
                }
                
            }
        }
        private static void populateConfig()
        {
            XmlNodeList secMapNodes = xdoc.SelectNodes("//pagemaping/securitymaping");
            
            foreach (XmlNode secMapNode in secMapNodes)
            {
                string role = secMapNode.Attributes["role"].Value;
                XmlNodeList mapNodes = secMapNode.SelectNodes("page");
                foreach (XmlNode mapNode in mapNodes)
                {
                    string fileName = mapNode.Attributes["name"].Value.ToLower();
                    if (mapTable.ContainsKey(fileName))
                    {
                        mapTable[fileName] = mapTable[fileName] + "," + role;
                    }
                    else
                    {
                        mapTable[fileName] = role;
                    }
                }
            }
        }
    }
}
